const conn = require('../db/db');

const login = (req, res) => {
    const body = req.body;
    const sql1 = "select * FROM user WHERE `username`=? AND `password`=?";
    conn.query(sql1, [body.username, body.password], (err, result) => {
        if (err) return res.send({
            msg: '用户登录失败',
            status: 501
        })
        if (result.length != 1) return res.send({
            msg: '用户登录失败',
            status: 502
        })
        res.send({
            msg: '登录成功',
            status: 200
        })
    })
}
const register = (req, res) => {
    const body = req.body;
    if (body.username.trim().length <= 0 || body.password.trim().length <= 0) {
        return res.send({
            msg: '请填写完整的表单数据后再注册用户！',
            status: 501
        })
    }
    const sql1 = 'select username from user where username=?';
    conn.query(sql1, body.username, (err, result) => {
        if (err) return res.send({
            msg: '用户名查重失败！',
            status: 502
        })
        if (result.length != 0) return res.send({
            msg: '用户名已被注册，请更换其它用户名后重新注册！',
            status: 503
        })
        const sql2 = 'insert into user set ?';
        conn.query(sql2, body, (err, result) => {
            if (err) return res.send({
                msg: '注册新用户失败！',
                status: 504
            })
            if (result.affectedRows !== 1) return res.send({
                msg: '注册新用户失败！',
                status: 505
            })
            res.send({
                msg: '注册新用户成功！',
                status: 200
            })
        })
    })
}
module.exports = {
    login,
    register
}